package gov.police.diary.controller;

import gov.police.diary.command.SearchCommand;
import gov.police.diary.command.SearchCommand.Column;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.ui.Model;

public abstract class AbstractSearchController {

    private static final List<SearchCommand.Column> COLUMNS = new ArrayList<SearchCommand.Column>();

    static {
        COLUMNS.add(new SearchCommand.Column("Nguoi Su Dung", "name"));
        COLUMNS.add(new SearchCommand.Column("Chuc vu", "title"));
        COLUMNS.add(new SearchCommand.Column("Noi Lam viec", "officeLink"));
        COLUMNS.add(new SearchCommand.Column("So dien thoai", "phoneNumbers"));
    }

    //@ModelAttribute(value = "command")
    public final void populateCommand(Model model, SearchCommand command) {
        if (!model.containsAttribute("command")) {
            model.addAttribute("command", command);
            command.setColumns(getTableColumns());
            command.setHeader(createPageHeader());
            command.setSearchAction(createSearchAction());
            command.setOtherActions(createOtherActions());
        }
    }

    public String render(RenderRequest request, RenderResponse response, SearchCommand command, Model model) {
        populateCommand(model, command);
        command.setEnd(command.getStart() * command.getCurrentPage());
        Object[] result = getResult(command.getKeywords(), command.getStart(), command.getEnd());
        command.setEnd(command.getStart() + result.length);
        command.setResult(result);
        System.out.println("command.getKeywords() = " + command.getKeywords());
        model.addAttribute("command", command);
        return getViewName();
    }

    protected List<Column> getTableColumns() {
        return COLUMNS;
    }

    public void search(ActionRequest request, ActionResponse response, SearchCommand command, Model model) {
        command.setTotal(getResultTotal(command.getKeywords()));
    }

    protected String getViewName() {
        return "phoneList";
    }

    protected abstract Object[] getResult(String keywords, long start, long end);

    protected abstract long getResultTotal(String keywords);

    protected abstract String createPageHeader();

    protected abstract String createSearchAction();

    protected abstract Map<String, String> createOtherActions();
}
